package com.example.webflux.controller;

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.time.Duration;
import java.util.stream.IntStream;

@RestController
public class AsyncFluxController {

    @GetMapping(value = "/api/stream/async", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> asyncStream() {
        return Flux.generate(sink -> {
            // 模拟异步数据生成（如从MQ或数据库轮询）
            String data = fetchDataFromExternalSource(); // 自定义方法
            sink.next(data);
        });
    }

    private String fetchDataFromExternalSource() {
        try {
            Thread.sleep(1000); // 模拟1秒延迟
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        return "Data-" + System.currentTimeMillis();
    }



//    // 示例2：JSON Stream 流式输出
//    @GetMapping(value = "/json", produces = MediaType.APPLICATION_STREAM_JSON_VALUE)
//    public Flux<GreetingController.DataItem> streamJson() {
//        return generateData()
//                .delayElements(Duration.ofMillis(500))  // 每0.5秒推送一个JSON对象
//                .map(data -> new GreetingController.DataItem(data,String.valueOf(System.currentTimeMillis())));  // 转换为JSON对象
//    }
//    // 模拟生成流式数据
//    public Flux<String> generateData() {
//        return Flux.fromStream(
//                IntStream.range(1, 100).mapToObj(i -> "Item-" + i)
//        );
//    }
}
